package com.fduss.artStore.dao.impl;

import com.fduss.artStore.dao.ArtworkSubjectDao;
import com.fduss.artStore.entity.ArtworkSubject;
import com.fduss.artStore.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by alex on 28/06/2017.
 */
public class ArtworkSubjectDaoImpl implements ArtworkSubjectDao {
    private JdbcUtil util;

    public ArtworkSubjectDaoImpl(){
        util = new JdbcUtil();
    }

    @Override
    public ArtworkSubject add(ArtworkSubject artworkSubject) {
        Connection conn = util.getConnection();
        String sql = "INSERT INTO `art`.`artworksubjects` " +
                "(`ArtWorkSubjectID`, `ArtWorkID`, `SubjectID`) VALUES (?, ?, ?)";
        PreparedStatement pst = null;
        boolean flag = false;

        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, artworkSubject.getArtWorkSubjectId());
            pst.setInt(2, artworkSubject.getArtWorkId());
            pst.setInt(3, artworkSubject.getSubjectId());
            pst.executeUpdate();
            flag = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }
        return flag ? artworkSubject: null;
    }

    @Override
    public void deleteByArtWork(int artworkId) {
        Connection conn = util.getConnection();
        String sql = "DELETE FROM `art`.`artworksubjects` WHERE `ArtWorkID`= ?";
        PreparedStatement pst = null;

        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, artworkId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }
    }

    @Override
    public void deleteBySubject(int subjectId) {
        Connection conn = util.getConnection();
        String sql = "DELETE FROM `art`.`artworksubjects` WHERE `SubjectID`= ?";
        PreparedStatement pst = null;
        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, subjectId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }

    }
}
